<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<title></title>
		<!-- <link rel="stylesheet" type="text/css" href="../../css/api.css" /> -->
		<link rel="stylesheet" type="text/css" href="../../css/style.css" />
		<style type="text/css">

			html,body {
				background: #F7F8FA;
				/*overflow: auto;
				-webkit-overflow-scrolling:touch;
				*/
			}
			.chart_form{ padding:15px 13px 75px;}
			.chart_form li{ overflow: hidden;line-height: 0;}
			.chart_form b{ display:block; text-align: center; font-size: 12px; font-weight: 400; color: #666; line-height: 35px;}
			.chart_form .chart_info{ position:relative; min-height: 45px; padding: 0 55px; margin-bottom:13px; text-align:left;}
			.chart_form .chart_info .avatar{ display:block; position: absolute; left: 0; top: 0; width: 40px; height: 40px; border-radius: 7px;}
			.chart_form .chart_info div{ text-align:left; display:inline-block; vertical-align: top; border:0px #ededed solid; max-width: 100%; box-sizing: border-box; padding: 12px 15px; line-height: 20px; background-color: #fff; font-size: 14px; color: #333; border-radius: 8px; overflow: hidden;}
			.chart_form .chart_info div i { position:absolute; left:48.5px; top:3px; width:7px; height:15px; background-image: url(../../image/dfpoint.png); background-size: 100% 100%; }
			.chart_form li.chart_mine .chart_info{ text-align:right;position:relative;}
			.chart_form li.chart_mine .chart_info div{  background-color:#3262F1; color:#fff; }
			.chart_form li.chart_mine .chart_info div i { position:absolute; left:inherit; right:48.5px; top:3px; width:7px; height:15px; background-image: url(../../image/mypoint.png); background-size: 100% 100%; }
			.chart_form li.chart_mine .chart_info .avatar{ right:0; left: inherit;}
			.chart_form li.chart_tu .chart_info div{ background-color:#fff; padding: 0px 80px 0px 0px; position: relative;}
			.chart_form li.chart_tu .chart_info h4{ display:block; font-size: 18px; font-weight: 600; color: #333; height: 25px; line-height: 25px; overflow: hidden;}
			.chart_form li.chart_tu .chart_info p{ height:20px; font-size:12px; overflow: hidden; margin-top: 7px;}
			.chart_form li.chart_tu .chart_info div > img{ position:absolute; right: 10px; top: 10px; width:60px; height: 60px;}
			
			.chart_form .chart_info_map{ position:relative; min-height: 45px; padding: 0 55px; margin-bottom:13px; text-align:left;}
			.chart_form .chart_info_map .avatar{ display:block; position: absolute; left: 0; top: 0; width: 40px; height: 40px; border-radius: 7px;}
			.chart_form .chart_info_map div{ text-align:left; display:inline-block; vertical-align: top; border:0px #ededed solid; max-width: 100%; box-sizing: border-box; padding: 0; line-height: 20px; background-color: #fff; font-size: 14px; color: #333; border-radius: 8px; overflow: hidden;}
			.chart_form .chart_info_map div i { position:absolute; left:48.5px; top:3px; width:7px; height:15px; background-image: url(../../image/dfpoint.png); background-size: 100% 100%; }
			.chart_form li.chart_mine .chart_info_map{ text-align:right;position:relative;}
			.chart_form li.chart_mine .chart_info_map div{  background-color:#3262F1; color:#fff; }
			.chart_form li.chart_mine .chart_info_map div i { position:absolute; left:inherit; right:48.5px; top:3px; width:7px; height:15px; background-image: url(../../image/mypoint.png); background-size: 100% 100%; }
			.chart_form li.chart_mine .chart_info_map .avatar{ right:0; left: inherit;}
			.chart_form li.chart_tu .chart_info_map div{ background-color:#fff; padding: 0px 80px 0px 0px; position: relative;}
			.chart_form li.chart_tu .chart_info_map h4{ display:block; border:1px red solid; font-size: 15px; font-weight: 600; color: #333; height: 35px; line-height: 35px; overflow: hidden;}
			.chart_form li.chart_tu .chart_info_map p{ height:20px; font-size:12px; overflow: hidden; margin-top: 7px;}
			.chart_form li.chart_tu .chart_info_map div > img{ position:absolute; right: 10px; top: 10px; width:60px; height: 60px;}
			
			
			
			
			
			.imgmsgdiv { border:0; padding: 0 !important; }
			.imgmsg { width: 100px; height:auto;  border-radius: 8px; }
			.chart_form .chart_info .load { 
				display:block;
				position: absolute;
				top: 0;
				bottom: 0;
				right: 155px;
				margin:auto;
				padding: 7px;
			}
			.chart_form li.chart_mine .chart_info .load {
				left:155px; right: inherit;
			}
			
			.voicemsg { float:left;line-height:25px; }
			.voicemsg img { float:left;width:25px;height:25px; margin-right:10px; }
			@media only screen and (max-width: 720px) {
				.chart_box ul{ width:100%;}
			}
			.toast {
				background: rgba(0, 0, 0, 0.7);
				text-align: center;
				border-radius: 12px;
				color: #ffffff;
				position: fixed;
				z-index: 3;
				top: 45%;
				left: 50%;
				width: 150px;
				min-height: 0em;
				margin-left: -75px;
				margin-top: -80px;
			}
			.toast-content {
				font-size: 15px;
				margin: 0 0 15px;
			}
			#container{
                position:relative;
				margin: 15px 0;
				display: inline-block;

				height: 28px;
				width: 32px;
            }
 
            #container span{
                width: 5px;
                height: 5px;
                top:0px;
                position:absolute;
                background:#48b800;
                -webkit-animation: bodong 0.5s infinite  ease;
            }
 
            #container span:first-child{
                left:0;
                -webkit-animation-delay:.3s;
            }
 
            #container span:nth-child(2){
                left:7px;
                -webkit-animation-delay:.4s;
 
            }
            #container span:nth-child(3){
                left:14px;
                 -webkit-animation-delay:.6s;
            }
             #container span:nth-child(4){
                left:21px;
                 -webkit-animation-delay:.8s;
            }
            #container span:nth-child(5){
                left:28px;
                 -webkit-animation-delay:1s;
            }
			.divpadd { padding: 12px 15px; }
            
			.display-none { opacity: 0; }
			.dongtu { display:block; }
			.dongtu img { display:inline-block; width:50px; border:0px red solid; padding: 25px 0 10px; }
		</style>
	</head>
	<body>
		<div class="dialog display-none" id="dialog">
			<div class="toast">
				<div class="dongtu">
				<img src="../../image/chatboximg/voicew.png">
				<img src="../../image/chatboximg/voiced.gif">
				</div>
				<div class="toast-content">正在录音</div>
			</div>
		</div>
		<div class="chart_form" id="chartdiv">
			<ul id="chatlist">
			
			</ul>
			<script id="chatlist_template" type="text/template">
			{{ for (var i = 0, len = it.length; i < len; i++) { }}
				{{? it[i].msgtype == 1 }}
				<li class="{{=it[i].cssstr}}" data-msgid="{{=it[i].msgid}}">
					{{? it[i].showtime == 1 }}<b>{{=it[i].createtime}}<i></i></b>{{?}}
					<div class="chart_info">
					  <img src="{{=it[i].avatar}}" onerror="javascript:this.src='../../image/defaultimg.png';" class="avatar" />
						<div class="divpadd">
							<p>{{=it[i].msg}}</p>
							<i></i>
						</div>
					</div>
				</li>
				{{?? it[i].msgtype == 2 }}
				<li class="{{=it[i].cssstr}}" data-msgid="{{=it[i].messageId}}">
					{{? it[i].showtime == 1 }}<b>{{=it[i].createtime}}<i></i></b>{{?}}
					<div class="chart_info">
						<img src="{{=it[i].avatar}}" onerror="javascript:this.src='../../image/defaultimg.png';" class="avatar" />
						<div class="imgmsgdiv">
							<img tapmode onload="removeLoad(this)" onclick="openImage('{{=it[i].imageUrl}}')" src="{{=it[i].thumbPath}}" class="imgmsg" />
						</div>
						<img src="../../image/load.gif" id="load_{{=it[i].messageId}}" class="load" />
					</div>
				</li>
				{{?? it[i].msgtype == 3 }}
				<li class="{{=it[i].cssstr}}" data-msgid="{{=it[i].messageId}}">
					{{? it[i].showtime == 1 }}<b>{{=it[i].createtime}}<i></i></b>{{?}}
					<div class="chart_info">
						<img src="{{=it[i].avatar}}" onerror="javascript:this.src='../../image/defaultimg.png';" class="avatar" />
						<div style="width:100px;" tapmode onclick="play(this,'{{=it[i].voicePath}}','{{=it[i].cssstr}}');">
							<p class="voicemsg"><img src="../../image/chatboximg/{{=it[i].cssstr}}stop.png"> {{=it[i].duration}}''</p>
							<i></i>
						</div>
						
						<img src="../../image/load.gif" id="load_{{=it[i].messageId}}" class="load display-none" />
					</div>
				</li>
				{{?? it[i].msgtype == 4 || it[i].msgtype == 5 }}
				<li class="{{=it[i].cssstr}}" data-msgid="{{=it[i].messageId}}">
					{{? it[i].showtime == 1 }}<b>{{=it[i].createtime}}<i></i></b>{{?}}
					<div class="chart_info">
						<img src="{{=it[i].avatar}}" onerror="javascript:this.src='../../image/defaultimg.png';" class="avatar" />
						<div tapmode onclick="">
							<p class="voicemsg"><img src="../../image/chatboximg/chat.png"> 通话时长 {{=formatSeconds(it[i].duration / 1000)}}</p>
							<i></i>
						</div>
						
						<img src="../../image/load.gif" id="load_{{=it[i].messageId}}" class="load display-none" />
					</div>
				</li>
				{{?? it[i].msgtype == 6 }}
				<li class="{{=it[i].cssstr}}" data-msgid="{{=it[i].messageId}}">
					{{? it[i].showtime == 1 }}<b>{{=it[i].createtime}}<i></i></b>{{?}}
					<div class="chart_info_map">
						<img src="{{=it[i].avatar}}" onerror="javascript:this.src='../../image/defaultimg.png';" class="avatar" />
						<div tapmode data-lat="{{=it[i].lat}}" data-lon="{{=it[i].lon}}" onclick="showMap(this);">
							<h4 style="padding:10px 5px;">{{=it[i].address}}</h4>
							<img src="{{=it[i].imageUrl}}" alt="" style="width:100%; min-width:210px; height:100px; object-fit: cover;" />
							<i></i>
						</div>
						
						<img src="../../image/load.gif" id="load_{{=it[i].messageId}}" class="load display-none" />
					</div>
				</li>
				{{?}}
			{{ } }}
			</script>
		</div>

	</body>
	<script type="text/javascript" src="../../script/api.js"></script>
	<script type="text/javascript" src="../../script/app.js"></script>
	<script type="text/javascript" src="../../script/permission.js"></script>
	<script type="text/javascript" src="../../script/doT.js"></script>
	<script type="text/javascript">
		var rong;
		var db;//db模块
		var dfuid,dfavatar,dflocalavatar,dfnickname,myuid,myavatar,mylocalavatar,mynickname;

		var lastmsgtime = 0;//最后一条消息时间，超过10分钟聊天气泡中显示消息时间
		var firstdbmsgid = 0;//当前第一条消息ID，本地数据库ID
		
		var rong;
		var UIChatBox;
		var conId;
		apiready = function() {
			api.parseTapmode();
			rong = api.require('rongCloud2');
			
			UIChatBox = api.require('UIChatBox');
			fnInitChatBox();
			
			dfavatar = api.pageParam.dfavatar;
			dfuid = api.pageParam.dfuid;
			dfnickname = api.pageParam.dfnickname;
			mylocalavatar = api.pageParam.mylocalavatar;
			dflocalavatar = api.pageParam.dflocalavatar;
			
			api.getPrefs({
				key: 'user_info'
			}, function(ret, err) {
				if (ret && ret.value)
				{
					var userinfo = JSON.parse(ret.value);
					mynickname = userinfo.realname;
					myavatar = userinfo.avatar;
					myuid = userinfo.mobile;
					
					opendb();//初始化db数据库
				}
			});
			api.addEventListener({
                name: 'navitembtn'
            }, function(ret, err) {
                if (ret.type == 'left') {
					api.closeWin({
					});
                }
            });
			var winHeight = api.winHeight;
			UIChatBox.addEventListener({
					target: 'inputBar',
					name: 'move'
			}, function(ret, err) {
				if (ret) {
					pageDown(300);
				}
			});
			UIChatBox.addEventListener({
				target : 'recordBtn',
				name : 'press'
			}, function(ret, err) {
				$api.removeCls($api.byId('dialog'),'display-none');
 				sj1 = new Date().getTime();
				if (ret) {
					var pername = new Array('microphone','storage');
					var perdesc = '麦克风/存储';
					if (api.systemType == "android") {
						if(!confirmPerarr(pername,perdesc,'')){
							return;
						}
					}
					var savePath = 'fs://lysd_' + (+new Date()) + '.amr';
					api.startRecord({
						path : savePath
					});
				}
			});
			UIChatBox.addEventListener({
				target : 'recordBtn',
				name : 'press_cancel'
			}, function(ret, err) {
				stopRecord();//先停止录音
				$api.addCls($api.byId('dialog'),'display-none');
				var sj2 = new Date().getTime() - sj1;
				if (sj2 <= 2000) {
					stopRecord();
					api.toast({
						msg : '语音时间较短，请重新录音',
						duration : 1500,
						location : 'middle'
					});
				} else if (sj2 > 2000) {
					api.stopRecord(function(ret, err) {
						if (ret.duration > 0) {
							sendVoiceMsg(ret.path, ret.duration);
						}
					});
				}
			});
			UIChatBox.addEventListener({
				target : 'recordBtn',
				name : 'move_in'
			}, function(ret, err) {
				sj1 = new Date().getTime();
				if (ret) {
					var savePath = 'fs://lysd_' + (+new Date()) + '.amr';
					api.startRecord({
						path : savePath
					});
				}
			});
			UIChatBox.addEventListener({
				target : 'recordBtn',
				name : 'move_out_cancel'
			}, function(ret, err) {
				stopRecord();//先停止录音
				$api.addCls($api.byId('dialog'),'display-none');
				var sj2 = new Date().getTime() - sj1;
				if (sj2 <= 2000) {
					stopRecord();
					api.toast({
						msg : '语音时间较短，请重新录音',
						duration : 1500,
						location : 'middle'
					});
				} else if (sj2 > 2000) {
					api.stopRecord(function(ret, err) {
						//alert(JSON.stringify(ret));
						if (ret.duration > 0) {
							sendVoiceMsg(ret.path, ret.duration);
						}
					});
				}
			});
			api.addEventListener({
				name : 'new_msg'
			}, function(ret, err) {
				var html = '';
				if (ret.value.msg.targetId == dfuid) {
					var targetId = dfuid;
					var msg = ret.value.msg.content.text;
					var msgid = ret.value.msg.messageId;
					var imageUrl = '';
					var thumbPath = '';
					var voicePath = '';
					var duration = '';
					var lon = '',lat = '',address = '';
					var msgtype = 1;
					if (ret.value.msg.objectName == 'RC:TxtMsg') {
						msgtype = 1;
					} else if (ret.value.msg.objectName == 'RC:ImgMsg') {
						msgtype = 2;
						msg = '[图像消息]';
						imageUrl = ret.value.msg.content.imageUrl;
						thumbPath = ret.value.msg.content.thumbPath;
					} else if (ret.value.msg.objectName == 'RC:VcMsg') {
						msgtype = 3;
						msg = '[语音消息]';
						voicePath = ret.value.msg.content.voicePath;
						duration = ret.value.msg.content.duration;
					} else if (ret.value.msg.objectName == 'RC:VCSummary') {
						if(ret.value.msg.content.mediaType == 1) {
							msgtype = 4;
							msg = '[语音通话]';
							duration = ret.value.msg.content.duration;
						}
						else
						{
							msgtype = 5;
							msg = '[视频通话]';
							duration = ret.value.msg.content.duration;
						}
						
					} else if (ret.value.msg.objectName == 'RC:LBSMsg') {
						msgtype = 6;
						msg = '[位置]';
						lat = ret.value.msg.content.latitude;
						lon = ret.value.msg.content.longitude;
						imageUrl = ret.value.msg.content.imagePath;
						thumbPath = ret.value.msg.content.imagePath;
						address = ret.value.msg.content.poi;
					}
					var showtime = 0;
					if (ret.value.msg.objectName != 'RC:VCSummary') {
						var extramsg = $api.strToJson(ret.value.msg.content.extra);
						showtime = extramsg.showtime;
					}
					var cssstr = '';
					var avatar = '';
					if(ret.value.msg.senderUserId == myuid)
					{
						cssstr = "chart_mine";
						avatar = mylocalavatar;
					}
					else
					{
						avatar = dflocalavatar;
					}
					if(msgtype=='6')
					{
						//cssstr += " chart_tu";
					}
					if(msgtype != 4 && msgtype != 5) {
					var chatlist = [{
						"msgid":msgid,
						"createtime":getdate(ret.value.msg.sentTime),
						"avatar":avatar,
						"msgtype":msgtype,
						"msg":msg,
						"imageUrl":imageUrl,
						"thumbPath":thumbPath,
						"voicePath":voicePath,
						"duration":duration,
						"lon":lon,
						"lat":lat,
						"address":address,
						"cssstr":cssstr,
						"showtime":showtime
					}];
					lastmsgtime = ret.value.msg.sentTime;
					UpdateList(0,'chatlist','chatlist_template',chatlist,1);
					var newchat = chatlist[0];
					Saverecord(dfuid,myuid,$api.jsonToStr(newchat));//存储到本地记录
					Savedialogrecord($api.jsonToStr(newchat),ret.value.msg.sentTime);
					}
					rong.clearMessagesUnreadStatus({
						conversationType : 'PRIVATE',
						targetId : dfuid
					}, function(ret, err) {
						
					});
				}
			});
			var transformarr = [];
			for(var i=1; i<24; i++)
			{
				var index = i < 10 ? '0'+i : i;
				transformarr.push('widget://image/UIPullRefreshImg/pull_end_image_frame_'+index+'.png');
			}
			api.setCustomRefreshHeaderInfo({
				bgColor : '#F7F8FA',
				image : {
					pull : 'widget://image/UIPullRefreshImg/pull.png',
					transform : transformarr,
					load : transformarr
				}
			}, function(ret, err) {
				getLastMessages();
				setTimeout(function() {
					api.refreshHeaderLoadDone();
				}, 3000)
			});
		}
		
		function sendVoiceMsg(amrPath, duration) {
			//发送语音信息
			var targetId = dfuid;
			var createtime = new Date().getTime(); 
			var showtime = 0;
			if(getInervalMinute(lastmsgtime,createtime) > 10)
			{
				showtime = 1;
				//是否显示时间，距离上个消息超过10分钟显示时间
			}
			var extramsg = {"fromuid":myuid,"fromnickname":mynickname,"fromavatar":myavatar,"touid":dfuid,"tonickname":dfnickname,"toavatar":dfavatar,"showtime":showtime};

			rong.sendVoiceMessage({
				conversationType : 'PRIVATE',
				targetId : targetId,
				voicePath : amrPath,
				duration : duration,
				extra : $api.jsonToStr(extramsg)
			}, function(ret, err) {
				if (ret.status == 'prepare') {
					console.log(JSON.stringify(ret));
					var voicePath = ret.result.message.content.voicePath;
					var duration = ret.result.message.content.duration;
					var msgid = ret.result.message.messageId;
					var imageUrl = "";
					var thumbPath = "";

					lastmsgtime = createtime;
					var chatlist = [{
						"msgid":msgid,
						"createtime":getdate(createtime),
						"avatar":mylocalavatar,
						"msgtype":3,
						"msg":"[语音消息]",
						"imageUrl":imageUrl,
						"thumbPath":thumbPath,
						"voicePath":voicePath,
						"duration":duration,
						"reportID":0,
						"cssstr":"chart_mine",
						"showtime":showtime
					}];
					UpdateList(0,'chatlist','chatlist_template',chatlist,1);
					$api.removeCls($api.byId('load_'+msgid),'display-none');
					var newchat = chatlist[0];
					
					Saverecord(myuid,dfuid,$api.jsonToStr(newchat));//存储到本地记录
					Savedialogrecord($api.jsonToStr(newchat),0);
					
				} else if (ret.status == 'success') {
					var msgid = ret.result.message.messageId;
					$api.remove($api.byId('load_'+msgid));
				} else if (ret.status == 'error') {
					var msgid = ret.result.message.messageId;
					$api.attr($api.byId('load_'+msgid),'src','../../../image/err.png');
				}
				
			});
		
		}
		function removeLoad(obj) {
			$api.remove(obj.parentNode.nextSibling);
		}
		//打开数据库
		function opendb() {
			db = api.require('db');
			db.openDatabase({
				name : 'record'
			}, function(ret, err) {
				if (ret.status) {
					initdb();
				}
			});
		}
		//初始化数据库
		function initdb() {
			db.executeSql({
				name : 'record',
				sql : "CREATE TABLE IF NOT EXISTS 'chatlogs' ('ID' INTEGER PRIMARY KEY AUTOINCREMENT,'fromuid' VARCHAR(50),'touid' VARCHAR(50),'dialogname' VARCHAR(50),'content' TEXT,'createtime' INTEGER)"
			}, function(ret, err) {
				if (ret.status) {
					rong.getUnreadCount({
						conversationType: 'PRIVATE',
						targetId: dfuid
					}, function(ret, err) {
						if(ret.result>0)
						{
							getLatestNoReadMessages(dfuid, 'PRIVATE', ret.result);
						}
						else
						{
							ReadChatLog();
						}
						//api.toast({ msg: ret.result });
					})
					
				} else {
					api.alert({
						msg : '初始化失败！请重新打开/n' + JSON.stringify(err),
						buttons : ['确定']
					});
				}
			});
		}

		//获取最新的未读记录并写入本地
		function getLatestNoReadMessages(targetId, conversationType, count) {
			rong.getLatestMessages({
				conversationType : conversationType,
				targetId : targetId,
				count : count
			}, function(ret, err) {
				if (ret.status == 'success') {
					if (ret.result && ret.result.length > 0) {
						var chatlog = [];
						console.log(JSON.stringify(ret.result));
						for(var item in ret.result){
							//alert(ret.result[item].senderUserId+"?"+ret.result[item].targetId+'?'+ret.result[item].content.text);
							var msg = ret.result[item].content.text;
							var msgid = ret.result[item].messageId;
							var imageUrl = '';
							var thumbPath = '';
							var voicePath = '';
							var duration = '';
							var lat = '';
							var lon = '';
							var address = '';
							var msgtype = 1;
							if (ret.result[item].objectName == 'RC:TxtMsg') {
								msgtype = 1;
							} else if (ret.result[item].objectName == 'RC:ImgMsg') {
								msgtype = 2;
								msg = '[图像消息]';
								imageUrl = ret.result[item].content.imageUrl;
								thumbPath = ret.result[item].content.thumbPath;
							} else if (ret.result[item].objectName == 'RC:VcMsg') {
								msgtype = 3;
								msg = '[语音消息]';
								voicePath = ret.result[item].content.voicePath;
								duration = ret.result[item].content.duration;
							} else if (ret.result[item].objectName == 'RC:VCSummary') {
								if(ret.result[item].content.mediaType == 1) {
									msgtype = 4;
									msg = '[语音通话]';
									duration = ret.result[item].content.duration;
								}
								else
								{
									msgtype = 5;
									msg = '[视频通话]';
									duration = ret.result[item].content.duration;
								}
								
							} else if (ret.result[item].objectName == 'RC:LBSMsg') {
								msgtype = 6;
								msg = '[位置]';
								lat = ret.result[item].content.latitude;
								lon = ret.result[item].content.longitude;
								imageUrl = ret.result[item].content.imagePath;
								thumbPath = ret.result[item].content.imagePath;
								address = ret.result[item].content.poi;
							}
							var showtime = 0;
							if (ret.result[item].objectName != 'RC:VCSummary') {
								var extramsg = $api.strToJson(ret.result[item].content.extra);
								showtime = extramsg.showtime;
							}
							var cssstr = '';
							var avatar = '';
							if(ret.result[item].senderUserId == myuid)
							{
								cssstr = "chart_mine";
								avatar = mylocalavatar;
							}
							else
							{
								avatar = dflocalavatar;
							}
							if(msgtype=='6')
							{
								//cssstr += " chart_tu";
							}
							var msg_item = {
								"msgid":msgid,
								"createtime":getdate(ret.result[item].sentTime),
								"avatar":avatar,
								"msgtype":msgtype,
								"msg":msg,
								"imageUrl":imageUrl,
								"thumbPath":thumbPath,
								"voicePath":voicePath,
								"duration":duration,
								"lon":lon,
								"lat":lat,
								"address":address,
								"cssstr":cssstr,
								"showtime":showtime
							};
							chatlog.push(msg_item);	
						}
						if(chatlog.length > 0)
						{
							lastmsgtime = ret.result[0].sentTime;
						}
						//倒序输出
						chatlog.reverse();
						for(var item in chatlog){
							var newchat = chatlog[item];
							Saverecord(dfuid,myuid,$api.jsonToStr(newchat));//存储到本地记录
						}
						
					}
				}
				ReadChatLog();
				//标记已读
				rong.clearMessagesUnreadStatus({
					conversationType : 'PRIVATE',
					targetId : dfuid
				}, function(ret, err) {
					api.execScript({
						name: 'root',
						script: 'reloadUnreadCount();'
					});
				});
			})
		}
		//读取聊天记录
		function ReadChatLog() {
			var dialogname = '#'+myuid+'and'+dfuid+'#';
			db.selectSql({
				name : 'record',
				sql : "select * from chatlogs where dialogname='"+dialogname+"' order by ID desc limit 10"
			}, function(ret, err) {
				if (ret) {
					if (ret.data != '') {
						chatlog = [];
						console.log(JSON.stringify(ret.data));
						for(var item in ret.data){
							if(ret.data[item])
							{
								var content = ret.data[item].content;
								var jsonmsg = $api.strToJson(content); 
								var msg = jsonmsg.msg;
								var msgid = jsonmsg.msgid;
								var imageUrl = '';
								var thumbPath = '';
								var voicePath = '';
								var duration = '';
								var lat = '',lon = '',address = '';
								var msgtype = jsonmsg.msgtype;
								if (msgtype == 2) {
									msg = '[图像消息]';
									imageUrl = jsonmsg.imageUrl;
									thumbPath = jsonmsg.thumbPath;
								} else if (msgtype == 3) {
									voicePath = jsonmsg.voicePath;
									duration = jsonmsg.duration;
								} else if (msgtype == 4 || msgtype == 5) {
									duration = jsonmsg.duration;
								} else if (msgtype == 6) {
									imageUrl = jsonmsg.imageUrl;
									lat = jsonmsg.lat;
									lon = jsonmsg.lon;
									address = jsonmsg.address;
								}
								var showtime = jsonmsg.showtime;
								
								
								var cssstr = '';
								var avatar = '';
								if(ret.data[item].fromuid == myuid)
								{
									cssstr = "chart_mine";
									avatar = mylocalavatar;
								}
								else
								{
									avatar = dflocalavatar;
								}
								if(msgtype==6)
								{
									//cssstr += " chart_tu";
								}
								var msg_item = {
									"msgid":msgid,
									"createtime":jsonmsg.createtime,
									"avatar":avatar,
									"msgtype":msgtype,
									"msg":msg,
									"imageUrl":imageUrl,
									"thumbPath":thumbPath,
									"voicePath":voicePath,
									"duration":duration,
									"lat":lat,
									"lon":lon,
									"address":address,
									"cssstr":cssstr,
									"showtime":showtime
								};
								chatlog.push(msg_item);	
							}
						}
						if(chatlog.length > 0)
						{
							lastmsgtime = parseInt(ret.data[0].createtime);
							firstdbmsgid = parseInt(ret.data[chatlog.length-1].ID);
						}
						//倒序输出
						chatlog.reverse();
						console.log(JSON.stringify(chatlog));
						//渲染页面
						UpdateList(0,'chatlist','chatlist_template',chatlog,0);
					}
				} else {
					console.log(JSON.stringify(err))
				}
			})
		};
		//储存会话
		function Savedialogrecord(content,createtime) {
			eliminaterecord();//清楚以前的会话
			if(createtime==0)
			{
				createtime = new Date().getTime();
			}
			var dialogname = '#'+myuid+'and'+dfuid+'#';
			db.executeSql({
				name : 'record',
				sql : "insert into chatdialogs(dialogname,content,createtime) values('" + dialogname + "','" + content + "'," + createtime + ")"
			});
			api.sendEvent({
				name : 'chatdialoglist'
			});
		};
		function eliminaterecord() {
			var dialogname = '#'+myuid+'and'+dfuid+'#';
			//alert("delete from chatdialog where dialogname='" + dialogname + "'");
			db.executeSql({
				name : 'record',
				sql : "delete from chatdialogs where dialogname='" + dialogname + "'"
			});
		};
		//储存聊天记录
		function Saverecord(fromuid,touid,content) {
			var createtime = new Date().getTime(); 
			var dialogname = '#'+myuid+'and'+dfuid+'#';
			
			db.executeSql({
				name : 'record',
				sql : "insert into chatlogs(fromuid,touid,dialogname,content,createtime) values('" + fromuid + "','" + touid + "','" + dialogname + "','" + content + "'," + createtime + ")"
			});

		};
		
		//获取上页消息记录
		function getLastMessages() {
			var firstli = $api.first($api.byId('chatlist'),'li');
			var firstmsgid = $api.attr(firstli,'data-msgid');
			var dialogname = '#'+myuid+'and'+dfuid+'#';
			db.selectSql({
				name : 'record',
				sql : "select * from chatlogs where dialogname='"+dialogname+"' and ID<"+firstdbmsgid+" order by ID desc limit 10"
			}, function(ret, err) {
				if (ret) {
					api.refreshHeaderLoadDone();
					if (ret.data != '') {
						chatlog = [];
						console.log(JSON.stringify(ret.data));
						for(var item in ret.data){
							if(ret.data[item])
							{
								var content = ret.data[item].content;
								var jsonmsg = $api.strToJson(content); 
								
								var msg = jsonmsg.msg;
								var msgid = jsonmsg.msgid;
								var imageUrl = '';
								var thumbPath = '';
								var voicePath = '';
								var duration = '';
								var msgtype = jsonmsg.msgtype;
								if (msgtype == 2) {
									msg = '[图像消息]';
									imageUrl = jsonmsg.imageUrl;
									thumbPath = jsonmsg.thumbPath;
								} else if (msgtype == 3) {
									voicePath = jsonmsg.voicePath;
									duration = jsonmsg.duration;
								}
								var showtime = jsonmsg.showtime;
								
								
								var cssstr = '';
								var avatar = '';
								if(ret.data[item].fromuid == myuid)
								{
									cssstr = "chart_mine";
									avatar = mylocalavatar;
								}
								else
								{
									avatar = dflocalavatar;
								}
								//if(ret.result[item].msgtype=='3')
								//{
									//cssstr = "chart_mine chart_tu";
								//}
								var msg_item = {
									"msgid":msgid,
									"createtime":getdate(jsonmsg.createtime),
									"avatar":avatar,
									"msgtype":msgtype,
									"msg":msg,
									"imageUrl":imageUrl,
									"thumbPath":thumbPath,
									"voicePath":voicePath,
									"duration":duration,
									"cssstr":cssstr,
									"showtime":showtime
								};
								chatlog.push(msg_item);	
							}
						}
						if(chatlog.length > 0)
						{
							firstdbmsgid = parseInt(ret.data[chatlog.length-1].ID);
						}
						//倒序输出
						chatlog.reverse();
						//console.log(JSON.stringify(chatlog));
						//渲染页面
						UpdateList(firstmsgid,'chatlist','chatlist_template',chatlog,2);
					}
				} else {
					console.log(JSON.stringify(err))
				}
			})
		
		}
		
		function subString(str, len, hasDot) {
            var newLength = 0;
            var newStr = "";
            var chineseRegex = /[^\x00-\xff]/g;
            var singleChar = "";
            var strLength = str.replace(chineseRegex, "**").length;
            for (var i = 0; i < strLength; i++) {
                singleChar = str.charAt(i).toString();
                if (singleChar.match(chineseRegex) != null) {
                    newLength += 2;
                }
                else {
                    newLength++;
                }
                if (newLength > len) {
                    break;
                }
                newStr += singleChar;
            }

            if (hasDot && strLength > len) {
                newStr += "...";
            }
            return newStr;
        }
		function getInervalMinute(startDate, endDate) {
			//相差分钟数
            //var ms = endDate.getTime() - startDate.getTime();
			var ms = endDate - startDate;
            if (ms < 0) return 0;
            return Math.floor(ms/1000/60);
        }
		function getdate(timestamp) {
            var now = new Date(timestamp),
			y = now.getFullYear(),
			m = now.getMonth() + 1,
			d = now.getDate();
			return (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 5);
            //return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
        }
		//终止录音
		function stopRecord() {
			api.stopRecord(function(ret, err) {
			});
		}
		//播放录音
		function play(el, path, cssstr) {
			console.log(path);
			if(path != '')
			{
				if(cssstr == "chart_mine") {
					el.querySelector("img").src='../../image/chatboximg/playing.gif';
				}else{
					el.querySelector("img").src='../../image/chatboximg/chart_mineplaying.gif';
				}
				api.startPlay({
					path : path
				}, function() {
					if(cssstr == "chart_mine") {
						el.querySelector("img").src='../../image/chatboximg/chart_minestop.png';
					}else{
						el.querySelector("img").src='../../image/chatboximg/stop.png';
					}
					//el.querySelector("img").src='../../image/chatboximg/stop.png';
				});
			}
		}
		//滑动到底部
        function pageDown(time) {
			setTimeout(function() {
				api.pageDown({
					bottom: true,
					animate: true
				}, function(ret) {
					//console.log(JSON.stringify(ret));
				});
				
			}, time || 0)
        }
		function fnLoadImage(dataUrl) {
			if(dataUrl!=''){
				api.imageCache({
					url: dataUrl
				}, function(ret, err) {
				
					if(ret && ret.status == true){
						shipper_avatar = ret.url;
						
					}
					else
					{
						//ReadChatLog();
					}
					//
				});
			}
		}
		
		function fnInitChatBox() {
			var topmargin = 9;
			if (api.systemType == "android") {
				topmargin = 5;
			}
			UIChatBox.open({
				placeholder: '',
				autoFocus: false,
				styles: {
					topDivider:{                        //(可选项)顶部分割线配置
						width:0,                        //(可选项)顶部分割线的粗细，默认：0 
						color:'#fff'                    //(可选项)顶部分割线的颜色；默认：#000 ;支持图片设置(fs:// & widget://)
					},
					inputBar: {                         //（可选项）JSON对象；输入区域（输入框及两侧按钮）整体样式      
						borderColor: '#ededed',         //（可选项）字符串类型；输入框区域上下边框的颜色，支持 rgb，rgba，#；默认：'#d9d9d9'
						bgColor: '#ffffff'              //（可选项）字符串类型；输入框区域的整体背景色，支持 rgb，rgba，#；默认：'#f2f2f2' 
					},
					inputBox: {                         //（可选项）JSON对象；输入框样式
						borderColor: 'rgba(165, 171, 175, 0.6)',         //（可选项）字符串类型；输入框的边框颜色，支持 rgb，rgba，#；默认：'#B3B3B3'
						bgColor: '#fff',             //（可选项）字符串类型；输入框的背景色，支持 rgb，rgba，#；默认：'#f2f2f2'
						boardBgColor: '#f2f2f2',              //（可选项）字符串类型；面板的背景色(表情面板，附加面板)，支持 rgb，rgba，#；默认：'#f2f2f2'
						topMargin:topmargin, 
					},
					extrasBtn: {
						normalImg: 'widget://image/chatboximg/add.png'
					},
					keyboardBtn: {
						normalImg: 'widget://image/chatboximg/keyboard.png'
					},
					speechBtn: {
						normalImg: 'widget://image/chatboximg/cam.png'
					},
					recordBtn : {
						normalBg : '#fff',
						activeBg : '#E0E0E0',
						color : '#333',
						size : 15
					},
					sendBtn: {
						titleColor: '#fff',
						bg: '#008AD4' ,
						activeBg: '#f2f2f2',
						titleSize: 14
					}
				},
				extras: {
					titleSize: 12,
					titleColor: '#5D5D5D',
					btns: [{
						title: '图片',
						normalImg: 'widget://image/chatboximg/img.png'
					},{
						title: '语音通话',
						normalImg: 'widget://image/chatboximg/audio.png'
					},{
						title: '视频通话',
						normalImg: 'widget://image/chatboximg/vedio.png'
					},{
						title: '定位',
						normalImg: 'widget://image/chatboximg/position.png'
					}]
				}
			}, function( ret, err ){
				var eventType = ret.eventType;
				var msg = ret.msg;
				if (eventType == 'clickExtras') {
					if (ret.index == 0) {
						getPicture(0);
						pageDown(300);
					}
					else if (ret.index == 1) {
						sendCall('audio');
					}
					else if (ret.index == 2) {
						sendCall('video');
					}
					else if (ret.index == 3) {
						openMap();
					}
				}
				else if (eventType == 'send') {
					
					if ($api.trimAll(ret.msg) == '') {
						toast('不能发送空白消息');
					} else {
						var targetId = dfuid;
						var createtime = new Date().getTime(); 
						var showtime = 0;

						if(getInervalMinute(lastmsgtime,createtime) > 10)
						{
							showtime = 1;
							//是否显示时间，距离上个消息超过10分钟显示时间
						}
						var extramsg = {"fromuid":myuid,"fromnickname":mynickname,"fromavatar":myavatar,"touid":dfuid,"tonickname":dfnickname,"toavatar":dfavatar,"showtime":showtime};
						rong.sendTextMessage({
							conversationType : 'PRIVATE',
							targetId : targetId,
							text : msg,
							extra : $api.jsonToStr(extramsg)
						}, function(ret, err) {
							console.log(JSON.stringify(err));
							if (ret.status == 'prepare') {
								
							} else if (ret.status == 'success') {
								var msgid = ret.result.message.messageId;
								lastmsgtime = createtime;
								
								
								
								var chatlist = [{
									"msgid":msgid,
									"createtime":getdate(createtime),
									"avatar":mylocalavatar,
									"msgtype":1,
									"msg":msg,
									"imageUrl":"",
									"thumbPath":"",
									"voicePath":"",
									"duration":"",
									"lat":"",
									"lon":"",
									"address":"",
									"cssstr":"chart_mine",
									"showtime":showtime,
									"unreadMessageCount":0
								}];
								UpdateList(0,'chatlist','chatlist_template',chatlist,1);
								
								
								var newchat = chatlist[0];
								
								Saverecord(myuid,dfuid,$api.jsonToStr(newchat));//存储到本地记录
								Savedialogrecord($api.jsonToStr(newchat),0);
								
								
							}
						});
							
					}
				}
			});
		}
		function isChina(s){ 
			//判断路径是否有中文
			var patrn=/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi; 
			if(!patrn.exec(s)){ 
				return false; 
			}
			else{ 
				return true; 
			} 
		}
		function randomString(len) {
		　　len = len || 32;
		　　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		　　var maxPos = $chars.length;
		　　var pwd = '';
		　　for (i = 0; i < len; i++) {
		　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
		　　}
		　　return pwd;
		}
		function getPicture(index){
			var pername = 'photos';
			var perdesc = '相册/本地存储';
			var sourceType = 'library';
            if(index==1){
				sourceType = 'camera';
				pername = 'camera';
				perdesc = '相机/拍照';
			}
			if (api.systemType == "android") {
				if(pername == 'photos')
				{
					pername = 'storage';
				}
				if(!confirmPer(pername,perdesc,'')){
					return;
				}
			}		
			api.getPicture({
				sourceType : sourceType,
				encodingType : 'jpg',
				mediaValue : 'pic',
				destinationType: 'base64',
				quality : 100,
			}, function(ret, err) {
			// 获取图片数据并处理
				if (ret) {
					var imgSrc = ret.data;
					//alert(imgSrc);
					
					if (imgSrc != "") {
						if(isChina(imgSrc))
						{
							var base64imgSrc = ret.base64Data;
							//路径包含中文，转存并重命名
							var imageCachePath = api.cacheDir;
							var picname = randomString(32) + '.jpg';
							var trans = api.require('trans');
							trans.saveImage({
								base64Str: base64imgSrc,
								imgPath:imageCachePath,
								imgName:picname
							}, function(ret, err) {
								if (ret.status) {
									imgSrc = imageCachePath + '/' + picname;
									sendImgMsg(imgSrc);
								}
							});
						}
						else
						{
							sendImgMsg(imgSrc);
						}
					}
				}
			});
		}
		//打开图像
		function openImage(path) {
			var photoBrowser = api.require('photoBrowser');
			photoBrowser.open({
					images: [path],
					activeIndex: 0,
					//placeholderImg: 'widget://image/apicloud.png',
					bgColor: '#000'
			}, function(ret) {
				if (ret.eventType == 'click') {
					photoBrowser.close();
				}
			});
		}
		function sendCall(mediaType) {
			// 发起音视频聊天
			var pername = new Array('phone','microphone','camera');
			var perdesc = '麦克风/摄像头';
			if (api.systemType == "android") {
				if(!confirmPerarr(pername,perdesc,'')){
					return;
				}
			}
			var createtime = new Date().getTime(); 
			var showtime = 0;

			if(getInervalMinute(lastmsgtime,createtime) > 10)
			{
				showtime = 1;
				//是否显示时间，距离上个消息超过10分钟显示时间
			}
			var param = {
				dfuid: dfuid,
				dfavatar: dfavatar,
				dfnickname: dfnickname,
				mediaType: mediaType,
				opentype: 'invite',
				showtime: showtime
			};
			openNavWin('#fff','msgrongCloud_win','msgrongCloud_frm.html','',true,false,false,[],param);
			//api.execScript({
				//name: 'root',
				//script: 'callvedio(\''+$api.jsonToStr(param)+'\');'
			//});
		}
		function sendImgMsg(imgSrc) {
			//发送图片信息
			var targetId = dfuid;
			var createtime = new Date().getTime(); 
			var showtime = 0;
			if(getInervalMinute(lastmsgtime,createtime) > 10)
			{
				showtime = 1;
				//是否显示时间，距离上个消息超过10分钟显示时间
			}
			var extramsg = {"fromuid":myuid,"fromnickname":mynickname,"fromavatar":myavatar,"touid":dfuid,"tonickname":dfnickname,"toavatar":dfavatar,"showtime":showtime};
			rong.sendImageMessage({
				conversationType : 'PRIVATE',
				targetId : targetId,
				imagePath : imgSrc,
				extra : $api.jsonToStr(extramsg)
			}, function(ret, err) {
				if (ret.status == 'prepare') {
					console.log(JSON.stringify(ret));
					var msgid = ret.result.message.messageId;
					var imageUrl = ret.result.message.content.imageUrl;
					var thumbPath = ret.result.message.content.thumbPath;
					//alert(thumbPath+"222");
					lastmsgtime = createtime;
					var chatlist = [{
						"msgid":msgid,
						"createtime":getdate(createtime),
						"avatar":mylocalavatar,
						"msgtype":2,
						"msg":"[图像信息]",
						"imageUrl":imageUrl,
						"thumbPath":thumbPath,
						"voicePath":"",
						"duration":"",
						"reportID":0,
						"cssstr":"chart_mine",
						"showtime":showtime
					}];
					UpdateList(0,'chatlist','chatlist_template',chatlist,1);
					var newchat = chatlist[0];
					Saverecord(myuid,dfuid,$api.jsonToStr(newchat));//存储到本地记录
					Savedialogrecord($api.jsonToStr(newchat),0);
					
				} else if (ret.status == 'success') {
					var msgid = ret.result.message.messageId;
					$api.remove($api.byId('load_'+msgid));
				} else if (ret.status == 'error') {
					var msgid = ret.result.message.messageId;
					$api.attr($api.byId('load_'+msgid),'src','../../image/err.png');
				}
				
			});
			UIChatBox.closeBoard();
		
		}
		function showMap(obj) {
			//显示地图定位
			var address = $api.text(obj.firstElementChild);
			var lat = $api.attr(obj,'data-lat');
			var lon = $api.attr(obj,'data-lon');
			var param = {
				lat: lat,
				lon: lon,
				address: address
			}
			openNavWin('#ddd','mapposition_win','mapposition_frm.html','定位',false,false,true,[],param);
			
		}
		function openMap() {
			var pername = 'location';
			var perdesc = '定位';
			if (api.systemType == "android") {
				if(!confirmPer(pername,perdesc,'')){
					return;
				}
			}
			//打开地图发送定位
			var rightbtn = [{
				text: '发送',
				color:'#3262F1',
				fontSize:15
			}];
			openNavWin('#ddd','position_win','position_frm.html','定位',false,false,true,rightbtn,{});
		}
		function sendPosition(jsonstr) {
			var jsondata = $api.strToJson(jsonstr);
			//发送定位消息
			var targetId = dfuid;
			var createtime = new Date().getTime(); 
			var showtime = 0;

			if(getInervalMinute(lastmsgtime,createtime) > 10)
			{
				showtime = 1;
				//是否显示时间，距离上个消息超过10分钟显示时间
			}
			var extramsg = {"fromuid":myuid,"fromnickname":mynickname,"fromavatar":myavatar,"touid":dfuid,"tonickname":dfnickname,"toavatar":dfavatar,"showtime":showtime};
			rong.sendLocationMessage({
				conversationType : 'PRIVATE',
				targetId : targetId,
				latitude : jsondata.lat,
				longitude: jsondata.lon,
				poi: jsondata.address,
				imagePath: jsondata.imgpath,
				extra : $api.jsonToStr(extramsg)
			}, function(ret, err) {
				console.log(JSON.stringify(err));
				if (ret.status == 'prepare') {
					
				} else if (ret.status == 'success') {
					var msgid = ret.result.message.messageId;
					lastmsgtime = createtime;
					
					
					
					var chatlist = [{
						"msgid":msgid,
						"createtime":getdate(createtime),
						"avatar":mylocalavatar,
						"msgtype":6,
						"msg":'[位置]',
						"imageUrl":jsondata.imgpath,
						"thumbPath":jsondata.imgpath,
						"voicePath":"",
						"duration":"",
						"lat":jsondata.lat,
						"lon":jsondata.lon,
						"address":jsondata.address,
						"cssstr":"chart_mine",
						"showtime":showtime,
						"unreadMessageCount":0
					}];
					UpdateList(0,'chatlist','chatlist_template',chatlist,1);
					
					
					var newchat = chatlist[0];
					
					Saverecord(myuid,dfuid,$api.jsonToStr(newchat));//存储到本地记录
					Savedialogrecord($api.jsonToStr(newchat),0);
					
					
				}
			});
			UIChatBox.closeBoard();
		}
		//渲染数据
		function UpdateList(msgid,domId,templateId,jsondata,isAppend) {
			//isAppend 0表示填充html，1表示底部追加，2表示顶部追加
			//console.log(JSON.stringify(jsondata));
			var act_content = $api.byId(domId);
			var tempFn = doT.template($api.byId(templateId).innerHTML);
			var resultText = tempFn(jsondata);
			//alert(isAppend);
			if(isAppend == 0)
			{
				$api.html(act_content, resultText);
				
			}
			else if(isAppend == 1)
			{
				$api.append(act_content, resultText);
			}
			else if(isAppend == 2)
			{
				$api.prepend(act_content, resultText);
			}
			api.parseTapmode();
			if(isAppend != 2)
			{
				pageDown(300);
			}
			else
			{
				var liList = document.getElementById("chatlist").children;
				var sheight = 0;//新增内容高度
				for (var i = 0; i < liList.length; i++) {
					var curmsgid = $api.attr(liList[i],'data-msgid');
					if(curmsgid == msgid)
					{
						break;
					}
					var offset = $api.offset(liList[i]);
					sheight += offset.h;
				}
				document.body.scrollTop = sheight - 5;
			}
			//setTimeout(function() {
				//api.parseTapmode();
			//}, 3000)
		}
	</script>
</html>